import { ref, reactive, onMounted } from 'vue'
import request from '@/utils/request'

export function useCRUD(endpoint) {
  const data = ref([])
  const loading = ref(false)
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
  })
  const searchParams = ref({})

  const fetchData = async () => {
    loading.value = true
    try {
      const params = {
        page: pagination.currentPage,
        size: pagination.pageSize,
        ...searchParams.value
      }
      // 假设后端返回的数据结构是 { content: [...], totalElements: 100 }
      const response = await request.get(endpoint, { params })
      data.value = response.content
      pagination.total = response.totalElements
    } catch (error) {
      console.error('Failed to fetch data:', error)
      data.value = []
      pagination.total = 0
    } finally {
      loading.value = false
    }
  }

  const handleSearch = (params) => {
    searchParams.value = params
    pagination.currentPage = 1 // 搜索时回到第一页
    fetchData()
  }

  const handlePageChange = (page) => {
    pagination.currentPage = page
    fetchData()
  }

  const handleSizeChange = (size) => {
    pagination.pageSize = size
    pagination.currentPage = 1 // 更改每页大小时回到第一页
    fetchData()
  }

  onMounted(fetchData)

  return {
    data,
    loading,
    pagination,
    fetchData,
    handleSearch,
    handlePageChange,
    handleSizeChange
  }
}